import {request} from "../../util/request.js";
import dialog from "../../util/dialog.js";
import "../../style/basic.less";
import "./auth.less";
let authTimer = null;
export default {
    template:` 
            <div class="form-group">
                <label>模块授权(授权区域仅站点创始人可见)</label>
                <p class="alert alert-success" v-if="status === 1">
                    授权成功，授权过期时间{{past_date}}
                </p>
                <p class="alert alert-warning" v-else-if="status === 4">
                    授权即将过期{{past_date}}
                    <button type="button" class="btn btn-info btn-sm" @click="clickAuth">点击更新授权</button>
                </p>
                <p class="alert alert-warning" v-else>
                    模块未授权或者授权已过期
                    <button type="button" class="btn btn-info btn-sm" @click="clickAuth">点击授权</button>
                </p>
                
                <div id="auth-qrcode" v-if="qrcode.show">
                    <div class="box">
                        <div class="auth-qrcode-close" @click="closeQrcode"><span class="iconfont icon-guanbi"></span></div>
                        <img :src="qrcode.url" />
                        <h2>微信扫一扫开始授权</h2>
                    </div>
                </div>
                
            </div>     
            `,
    data:function(){
        return {
            status:0,  //0=本地未注册，1=正常，2=未授权，3=授权过期，4=即将过期
            past_date:"",  //授权码过期时间
            wx_appid:window.sysinfo.account.key,  //微信appid
            domain:"",  //网站域名
            url:"https://w7de.kuyuan.vip/app/index.php?i=2&c=entry&do=cloud&m=kuyuan_check",
            identity:"",  //唯一验证码
            qrcode:{
                show:false,
                url:""
            },
            listen_second:20  //监听超时秒数，超时自动关闭授权二维码
        }
    },
    props:{
        module:{
            type:String
        }
    },
    created:function(){
        this.trimWebUrl();
        this.getCloud()
            .then(()=>{
                if(this.status === 0){
                    return this.registerCloud();
                }
            })
            .then((identity)=>{
                if(identity) return this.registerLocal(identity);
            });
    },
    methods: {
        /**
         * 处理网站域名（不包含http）
         */
        trimWebUrl(){
            let url = window.sysinfo.siteroot.slice(0,-1);
            if(url.indexOf("http://") > -1){
                url = url.slice(7);
            }else{
                url = url.slice(8);
            }
            this.domain = url;
        },
        /**
         * 获取授权云服务信息
         */
        getCloud(){
            return new Promise((success)=>{
                request("cloud/getCloud",{
                    module:this.module,
                    wx_appid:this.wx_appid
                })
                    .then((res)=>{
                        if(res.data.status === "success"){
                            let data =res.data.data;
                            let timestamp = parseInt(new Date().getTime() / 1000);
                            this.identity = data.identity;
                            if(data.authority === ""){
                                this.status = 2;
                            }else if(timestamp > parseInt(data.past_time)){
                                if((timestamp - parseInt(data.past_time)) < 86400){
                                    this.past_date = data.past_date;
                                    this.status = 4;
                                }else{
                                    this.status = 3;
                                }
                            }else{
                                this.status = 1;
                                this.past_date = data.past_date;
                            }
                        }else{
                            this.status = 0;
                        }
                        success();
                    });
            });
        },
        /**
         * 注册云服务
         */
        registerCloud(){
            return new Promise((success)=>{
                request("cloud/register",{
                    module:this.module,
                    wx_appid:this.wx_appid,
                    domain:this.domain
                },this.url)
                    .then((res)=>{
                        if(res.data.status === "success"){
                            this.identity = res.data.data;
                            success(res.data.data);
                        }
                    });
            });
        },
        /**
         * 注册本地云服务
         */
        registerLocal(identity){
            return new Promise(()=>{
                request("cloud/register",{
                    module:this.module,
                    identity:identity,
                    wx_appid:this.wx_appid
                })
                    .then((res)=>{
                        console.log(res);
                    });
            });
        },
        /**
         * 点击授权按钮
         */
        clickAuth(){
            this.qrcode.show = true;
            this.getAuthQrcode()
                .then(()=>{
                    //开启监听授权定时器
                    clearInterval(authTimer);
                    let timer = 0;
                    authTimer = setInterval(()=>{
                        if(timer >= this.listen_second){
                            this.closeQrcode();
                        }else{
                            this.listenCloudAuth();
                            timer += 0.5;
                        }
                    },500);
                });
        },
        /**
         * 关闭授权二维码
         */
        closeQrcode(){
            clearInterval(authTimer);
            this.qrcode.show = false;
        },
        /**
         * 获取授权二维码
         */
        getAuthQrcode(){
            return new Promise((success)=>{
                request("cloud/getAuthQrcode",{
                    identity:this.identity
                },this.url)
                    .then((res)=>{
                        if(res.data.status === "success"){
                            this.qrcode.url = res.data.data;
                            success();
                        }
                    });
            });
        },
        /**
         * 监听云服务授权成功
         */
        listenCloudAuth(){
            request("cloud/listenCloudAuth",{
                identity:this.identity
            },this.url)
                .then((res)=>{
                    if(res.data.status == "success"){
                        this.authSuccess(res.data.data);
                    }
                });
        },
        /**
         * 授权成功，更改本地授权码，授权过期时间
         */
        authSuccess(data){
            request("cloud/setAuthority",{
                identity:this.identity,
                authority:data.authority,
                past_time:data.past_time
            })
                .then((res)=>{
                    if(res.data.status === "success"){
                        this.getCloud();
                        this.closeQrcode();
                        dialog.alert(this,"授权成功");
                    }else{
                        dialog.alert(this,"授权失败，请重试");
                        this.closeQrcode();
                    }
                });
        }
    }
};